<template>
	<view>
		<cu-custom :bgColor="globalColor" :isBack="true">
		    <block slot="content">视频/图片解析</block>
		</cu-custom>
		<view class="text-area">
			<textarea maxlength="-1" :value="textareaAValue" placeholder="请输入视频或图片地址"  style="height: 160px;padding-left: 10px;padding-top: 10px;width: 100%;" @input.stop="textareaBInput" ></textarea>
		</view>
		<view class="box">
			<view class="cu-bar btn-group">
				<button v-if="prizeType == 0" class="cu-btn" :class="globalColor" style="color: white;height: 35px;font-size: 16px;" @click="toSetData">粘贴链接</button>
				<button class="cu-btn shadow" :class="globalColor" style=" color: white;height: 35px;font-size: 16px;"  @click="clearText">清空链接</button>
			</view>
		</view>
		<view class="padding-sm flex flex-direction" style="margin-top: -8px;">
			<button class="cu-btn lg " :class="globalColor" style="color: white;height: 35px;font-size: 16px;" @click="adAnalyse()">立即解析</button>
		</view>
		<view class="teach">
			<text @click="page(1)">去水印相关问题</text>
		</view>
		
		
		<template v-if="result">
			<uni-card>
				<view class="tap-warp">
					<view v-if="videosList.length" class="tap-item" :class="tapType == 'video' ? 'active' : ''" @click="tapType='video'">
						<uni-icons type="videocam" size="22" color="#1890FF"></uni-icons>
						<text>视频</text>
					</view>
					<view class="tap-item" :class="tapType == 'img' ? 'active' : ''" @click="tapType='img'">
						<uni-icons type="image" size="18" color="#1890FF"></uni-icons>
						<text>图片</text>
					</view>
					<view class="tap-item" :class="tapType == 'text' ? 'active' : ''" @click="tapType='text'">
						<uni-icons type="list" size="18" color="#1890FF"></uni-icons>
						<text>文案</text>
					</view>
				</view>
				<template v-if="tapType == 'video'">
					<swiper class="swiper-box" @change="changeVideo" :current="videoIndex">
						<swiper-item v-for="(item ,index) in videosList" :key="index">
							<view class="swiper-item">
								<video style="width: 100%;height: 200px;" class="video-play" :poster="cover" v-bind:src="item" />
							</view>
						</swiper-item>
					</swiper>
					<view class="swiper-tip">
						<text>滑动切换下一个</text>
						<text>{{videoIndex+1}}/{{videosList.length}}</text>
					</view>
					<view class="operate-warp">
						<view class="operate-btn plain" @click="copyVideoLink(videoIndex)">
							<uni-icons type="redo" size="18" color="#1890FF"></uni-icons>
							复制链接
						</view>
						
						<view class="operate-btn primary" @click="downFile(1,videosList[videoIndex])">
							<uni-icons type="download" size="18" color="#fff"></uni-icons>
							下载视频
						</view>
					</view>
				</template>
				<template v-if="tapType == 'img'">
					<swiper class="swiper-box" @change="changeImg" :current="imgIndex">
						<swiper-item v-for="(item ,index) in picsList" :key="index">
							<view class="swiper-item">
								<image :src="item" class="swiper-item-img" mode="heightFix" @click="previewPic(index)" />
							</view>
						</swiper-item>
					</swiper>
					<view class="swiper-tip">
						<text>滑动切换下一个</text>
						<text>{{imgIndex+1}}/{{picsList.length}}</text>
					</view>
					<view class="operate-warp">
						<view class="operate-btn plain" @click="copyImgLink(imgIndex)">
							<uni-icons type="redo" size="18" color="#1890FF"></uni-icons>
							复制链接
						</view>
			
						<view class="operate-btn" @click="downFile(2,picsList[imgIndex])">
							<uni-icons type="download" size="18" color="#1890FF"></uni-icons>
							下载图{{imgIndex+1}}
						</view>
			
						<view class="operate-btn" @click="downAllFun">
							<uni-icons type="help" size="18" color="#1890FF"></uni-icons>
							下载全部
						</view>
					</view>
				</template>
				
				<template v-if="tapType == 'text'">
				
					<view class="">
						<view class="desc-warp">
							{{respData.desc}}
						</view>
						<view class="operate-btn plain" @click="copyTitle">
							<uni-icons type="redo" size="18" color="#1890FF"></uni-icons>
							复制文案
						</view>
					</view>
				</template>
				
			</uni-card>
			
		</template>
		
		
		<!-- <view v-if="result">
			<view class="padding-sm">
				<video class="video-play" :poster="cover"  v-bind:src="videoUrl"/>
			</view>
			<cmd-progress :percent="percent" :success-percent="percent" stroke-color="white" custom>
			  <text style="color: #009688;">{{percent}}%</text>
			</cmd-progress>
			<view class="box">
				<view class="cu-bar btn-group">
					<button class="cu-btn bg-orange shadow-blur" style="height: 30px;font-size: 16px;" @click="copyMvUrl">复制无水印链接</button>
					<button class="cu-btn bg-green  shadow" style="height: 30px;font-size: 16px;" @click="downFile(1,videoUrl)">保存到手机</button>
				</view>
			</view>
			<view class="box" v-if="null != cover">
				<view class="cu-bar btn-group">
					<button class="cu-btn bg-blue shadow-blur" style="height: 30px;font-size: 16px;" v-if="null != cover" @click="copyMusic(3,cover)">复制封面链接</button>
					<button class="cu-btn bg-orange  shadow" style="height: 30px;font-size: 16px;" v-if="null != cover" @click="downFile(2,cover)">保存封面</button>
				</view>
			</view>
			<view class="box">
				<view class="cu-bar btn-group">
					<button class="cu-btn bg-blue shadow-blur" style="height: 30px;font-size: 16px;" v-if="null != cover" @click="copyTitle()">复制标题</button>
				</view>
			</view>
			<view class="teach" style="width: 100%;height: 20px;" @click="page(27)" >
				<text >下载失败？点我查看下载教程</text>
			</view>
		</view> -->
		<!-- <view style="margin-top: 8px;" v-if="showAd">
			<ad :unit-id="ad" ad-type="video" ad-theme="white"></ad>
		</view> -->
		<!-- #ifdef MP-WEIXIN -->
		<!-- 小程序隐私协议 -->
		<privacy-popup ref="privacyPopup" @agree="checkAction"></privacy-popup>
		<!-- #endif -->
		<!-- <ratePopup ref="ratepopup"></ratePopup> -->
	</view>
</template>

<script>
	import CryptoJS from '../../node_modules/crypto-js/crypto-js.js';
	import cmdProgress from "@/components/cmd-progress/cmd-progress.vue"
	
	export default {
		components: {
			cmdProgress
		},
		data() {
			return {
				textareaAValue:'',
				rewardedVideoAd:null,
				currentTimeStamp:null,
				videoUrl:'',
				percent:0,
				fileStatus:'success',
				rewardedVideoAd:null,
				videoType:0,
				prizeContent:getApp().globalData.prizeContent,
				rewardedVideoAd:null,
				author:getApp().globalData.author,
				cover:null,
				music:null,
				title:null,
				result:false,
				fileType:0,
				downLoadType:1,
				showAd:false,
				ad:'',
				adError:0,
				size:0,
				playAddr:'',
				analyseType:1,
				downLoadType:2,
				prizeType:getApp().globalData.prizeType,
				type: null,
				flag: null,
				fileUrl: null,
				actionType:1,  //1-下载视频  //2-剪切版
				globalColor: getApp().globalData.globalColor,
				coverList:['https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2401491928,907118315&fm=27&gp=0.jpg','https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2401491928,907118315&fm=27&gp=0.jpg','https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2401491928,907118315&fm=27&gp=0.jpg'],
				
				tapType: 'video',
				videoIndex: 0,
				imgIndex: 0,
				respData: {},
				picsList: [],
				videosList: []
			}
		},
		onLoad(options) {
			this.ad = getApp().globalData.toolAd
			this.showAd = true
			if(null != options.link && typeof(options.link) != 'undefined') {
				this.textareaAValue = options.link
				this.adAnalyse()
			}
			if(null != options.videoMsg && typeof(options.videoMsg) != 'undefined') {
				this.videoUrl = options.videoMsg;
				this.result = true
			}
			this.createRewardVideo()
			this.createRewardCard();
			if(null != options.skipType && typeof(options.skipType) != 'undefined') {
				this.textareaAValue = getApp().globalData.analyseUrl
				this.adAnalyse()
			}
		},
		onShow() {
			//this.checkCliboard()
		},
		onShareAppMessage(res) {
			return {
			  title: '视频去水印工具，背景音乐提取，图片去水印，超多好用工具 快来试试吧~',
			  path: '/pages/index/index',
			  imageUrl: 'http://parse-video-server.oss-cn-hangzhou.aliyuncs.com/share.png'
			}
		},
		onShareTimeline: () => {
		  return {
			title: getApp().globalData.shareTitle,
		    query: "/pages/index/index",
		    imageUrl:getApp().globalData.sharePic
		  }
		},
		methods: {
			checkAction() {
				if(this.actionType == 1) {
					this.downFileFun();
				}else {
					this.toSetData();
				}
			},
			adAnalyse:function() {
				var that = this;
				this.analyseType = 1;
				if(getApp().globalData.fileType == 0) {
					that.videoAnalyse();
					return;
				}
				uni.showLoading({
					title: '初始化资源'
				})
				uni.request({
					url: that.$reqUrl + "/lyz/getUserAdTimes?uid=" + getApp().globalData.uid,
					method: 'get',
					success(res) {
						if (res.data.data < getApp().globalData.watchTimes && that.adError == 0) {
							uni.showModal({
								content: getApp().globalData.adTip,
								success(confirmRes) {
									if (confirmRes.confirm) {
										that.rewardedVideoAd.show().catch(() => {
											that.rewardedVideoAd.load()
												.then(() => that.rewardedVideoAd.show())
												.catch(err => {
													that.videoAnalyse()
												})
										})
									} else {
										uni.showToast({
											title: '看完广告才可以使用',
											icon: 'none'
										})
									}
								}
							})
						} else {
							that.videoAnalyse()
						}
					},
					complete(res) {
						uni.hideLoading()
					}
				})
			},
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
			},
			textareaBInput(e) {
				this.textareaAValue = e.detail.value
			},
			clearText() {
				console.log("==================")
				this.textareaAValue = ''
			},
			toSetData() {
				var that = this;
				that.actionType = 2;
				uni.getClipboardData({
					success: (res) => {
						uni.hideToast()
						uni.showToast({
							icon:'success',
							title:'粘贴成功'
						})
						if(res.data.length < 2) {
							uni.showModal({
								content:'您的剪切板没有链接哦'
							})
						}else {
							that.textareaAValue = res.data
						}
					},
					fail: function(e){
						console.log("============剪切板异常码=============")
						console.log(e.errno)
						if(e.errno === 1512001) {
							console.log(e)
							uni.showModal({
								title: "提示",
								content:'没有检测到有效的链接地址',
								showCancel:!1
							})
						}else {
							uni.showModal({
								title: "提示",
								content:'粘贴链接失败，请手动粘贴到输入框',
								showCancel:!1
							})
						}
					}
				})
			},
			page(type) {
				console.log("=========================="+type)
				if(type == 1) {
					uni.navigateTo({
						url:'../parse/parse?conId=100019'
					})
				}else{
					uni.navigateTo({
						url:'../parse/parse?conId=27'
					})
				}
			},
			skipToPrize:function (){
				uni.previewImage({
					urls: [getApp().globalData.prizeImg],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏']
					}
				});
			},
			videoAnalyse: function() {
				var that = this;
				var unPlatList = getApp().globalData.skipList;
				for(var i=0;i<unPlatList.length;i++) {
					var platEntity = unPlatList[i];
					if(that.textareaAValue.indexOf(platEntity.url) != -1) {						
						if(platEntity.status == 0) {
							uni.showModal({
								content:platEntity.title
							})
						}else if(platEntity.status == 1) {
							console.log("开始跳转")
							uni.navigateToMiniProgram({
							  appId: platEntity.appId
							})
						}					
						return;
					}
				}	
				//执行解析
				uni.showLoading({
					title: '解析中',
					mask: true
				});
				that.result = false;
				let timestamp = Date.parse(new Date()) / 1000
				console.log(that.textareaAValue + '######' + timestamp + '######' + getApp().globalData
					.token + '######' + that.$source)
				uni.request({
					url: that.$reqUrl + '/lyz/platWeChatAnalyse',
					data: {
						link: that.textareaAValue,
						source: that.$source,
						timestamp: timestamp,
						signature: that.encrypt(that.textareaAValue + '######' + timestamp + '######' + getApp().globalData.token + '######' + that.$source),
						version: 1
					},
					header: {
						token: getApp().globalData.token
					},
					method: "POST",
					success: (res) => {
						console.log(res.data)
						that.respData = res.data.data;
						that.picsList = that.respData.pics ? that.respData.pics  : [that.respData.cover]
						//that.videosList = that.respData.videos ? that.respData.videos  : [that.respData.playAddr],
						if(that.respData.videos){
							that.videosList = that.respData.videos
						} else if(that.respData.playAddr){
							that.videosList = [that.respData.playAddr]
						}
						that.tapType = that.videosList.length ? 'video' : 'img'
						//视频大小超过50M
						if (res.data.code === '0002' || res.data.code === '0009') {
							uni.showModal({
								content: res.data.message
							})
						} else if (res.data.code === '0001') {
							var videoMsg = res.data.data;
							getApp().globalData.title = videoMsg.desc;
							
							//类型
							// if (videoMsg.type == 2) {
							// 	getApp().globalData.pics = JSON.stringify(videoMsg);
							// 	uni.navigateTo({
							// 		url: '../picInfo/picInfo?initAd=true'
							// 	});
							// } else {
								getApp().globalData.playAddr = videoMsg.playAddr;
								getApp().globalData.cover = videoMsg.cover;
								getApp().globalData.title = videoMsg.desc;
								getApp().globalData.size = videoMsg.size;
								that.videoUrl = videoMsg.playAddr;
								that.cover = videoMsg.cover;
								that.title = videoMsg.desc;
								that.music = videoMsg.music;
								that.size = videoMsg.size;
								that.result = true;
							// }
						} else {
							uni.showModal({
								content: '未知错误，请联系作者进行解决'
							})
						}
					},
					fail(res) {
						uni.showModal({
							content: '服务器维护中 请稍后重试 有问题请联系作者'
						})
					},
					complete(res) {
						uni.hideLoading();
					}
				});
			},
			encrypt:function(word){
			    var key = CryptoJS.enc.Utf8.parse(getApp().globalData.access);
			    var srcs = CryptoJS.enc.Utf8.parse(word);
			    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
			    return encrypted.toString();
			},
			createRewardVideo() {
				var that = this;
				try{
					this.rewardedVideoAd = wx.createRewardedVideoAd({adUnitId: getApp().globalData.videoAdReward})
					this.rewardedVideoAd.onError(err => {
					  console.log(err)
					  that.adError = 1
					})
					
					//监听广告是否看完
					that.rewardedVideoAd.onClose(res => {							
						if (res && res.isEnded) {
							console.log("===========广告看完了===========")
							uni.request({
								url:that.$reqUrl + "/lyz/updateUserAdTimes?uid="+getApp().globalData.uid,
								method:'get',
								success: (res) => {
									console.log(res.data)
								}
							})
						    if(that.analyseType == 1) {
								that.videoAnalyse()
							}else {
								if(that.downLoadType == 2) {
									that.startDownLoad(that.downLoadType, that.cover)
								}else {
									that.startDownLoad(that.downLoadType, that.videoUrl)
								}
							}
						} else {
						  uni.showModal({
							content:getApp().globalData.adTip
						  })
						}
					})  
				}catch(e){
					console.log(e)
					that.adError = 1
				}		
			},
			createRewardCard() {
				let interstitialAd = null
				if(wx.createInterstitialAd){
				      interstitialAd = wx.createInterstitialAd({ adUnitId: getApp().globalData.videoAdCard})
				      interstitialAd.onLoad(() => {
				        console.log('onLoad event emit')
				      })
				      interstitialAd.onError((err) => {
				        console.log('onError event emit', err)
				      })
				      interstitialAd.onClose((res) => {
				        console.log('onClose event emit', res)
				      })
					  //一天出现一次就够了 并且第一次不出现
					  const timestamp = new Date().getTime() / 1000;
					  console.log(timestamp);
					  var curTime = uni.getStorageSync('cardAds');
					  if(curTime) {
						   console.log("当前间隔" + (timestamp - curTime));
					  }
					  console.log("当前的curTime:" + curTime)
					  if(!curTime) {
						  console.log("第一次 需要展示插屏广告");
						  uni.setStorageSync('cardAds',timestamp)
						
					  }else if(!curTime && (timestamp - curTime) > (60 * 60 * 6)) {
						  console.log("过了时间限制 需要展示插屏" + (timestamp - curTime));
					  }else {
						  console.log("=========不满足插屏展示条件============")
						  return;
					  }
					  
					  
					  interstitialAd.show().catch((err) => {
						console.error(err)
					  })
					 
				}
			},
			copyMusic(type,music) {
				var that = this;
				uni.setClipboardData({
					data: that.cover,
					success: function () {
						uni.setStorageSync(music,music)
						uni.showModal({
							content:'已经复制链接到剪切板'
						})
					}
				});
			},
			copyMvUrl() {
				var that = this;
				uni.setClipboardData({
					data: that.videoUrl,
					success: function () {
						uni.hideToast()
						uni.show
						uni.setStorageSync(that.videoUrl,that.videoUrl)
						uni.showModal({
							content:'复制成功'
						})
					}
				});
			},
			copyTitle() {
				var that = this;
				uni.setClipboardData({
					data: that.title,
					success: function () {
						
					}
				});
			},
			skipToPrize:function (){
				var that = this;
				if(getApp().globalData.prizeType == 1) {
					uni.previewImage({
						urls: [getApp().globalData.prizeImg],
						longPressActions: {
							itemList: ['发送给朋友', '保存图片', '收藏']
						}
					});
				}else {
					uni.navigateToMiniProgram({
					  appId: 'wx18a2ac992306a5a4',
					  path:getApp().globalData.prizePath		  
					})
				}
			},
			skipToWeb:function(type) {
				uni.navigateTo({
					url:'../parse/parse?conId=5'
				})
			},
			
			downFile(type, fileUrl) {
				var that = this;
				that.type = type
				that.actionType = 1;
				that.fileUrl = fileUrl
				console.log(this.$refs.privacyPopup)
				this.$refs.privacyPopup.proactive();
				that.downLoadType = type
				that.analyseType = 2;
			},
			
			downFileFun() {
				var that = this;
				uni.showLoading({
					title:'初始化资源'
				})
				uni.request({
					url:that.$reqUrl + "/lyz/getUserAdTimes?uid="+getApp().globalData.uid,
					method:'get',
					success(res) {
						if(res.data.data < getApp().globalData.watchTimes && that.adError == 0) {
							uni.showModal({
								content:getApp().globalData.adTip,
								success(confirmRes) {
									if(confirmRes.confirm) {
										that.rewardedVideoAd.show().catch(() => {
											that.rewardedVideoAd.load()
											  .then(() => that.rewardedVideoAd.show())
											  .catch(err => {that.startDownLoad(that.type,that.fileUrl)})
										  })
									}else {
										uni.showToast({
											title:'看完广告即可下载视频哟',
											icon:'none'
										})
									}
								},
								fail(failRes) {
									
								}
							})
						}else {
							that.startDownLoad(that.type,that.fileUrl)
						}
					},complete(res) {
						uni.hideLoading()
					}
				})
			},
			startDownLoad(type, fileUrl,flag) {
				var that = this;
				uni.showLoading({
					title: '加载下载资源中'
				})
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success() {
						that.percent = 0;
						that.fileStatus = 'active'
						//请求视频真实地址
						uni.request({
							url: that.$reqUrl + '/lyz/getDownLoadFileUrl',
							method: "POST",
							timeout:35000,
							data: {
								link: fileUrl,
								type: type,
								source: that.$source,
								origin:flag
							},
							success: (res) => {
								uni.hideLoading();
								uni.showLoading({
									title:'下载中'
								})
								if (res.data.code === '0001') {
									var downloadFileUrl = res.data.data;
									console.log(downloadFileUrl)
									const downloadTask = uni.downloadFile({
										url: res.data.data, 
										success: (res) => {
											if (res.statusCode === 200) {
												uni.hideLoading();
												if (type == 1) {
													uni.saveVideoToPhotosAlbum({
														filePath: res.tempFilePath,
														success: function () {
															that.percent = 100;
															uni.showToast({
																icon:'success',
																duration:2000,
																title:'已保存到相册'
															})
															
															//that.$refs.ratepopup.openRate()
														},
														fail: (errRes) => {
															that.targetMp4Download(type,downloadFileUrl)
														}
													});
													console.log("保存视频到相册")
												} else if (type == 2) {
													uni.saveImageToPhotosAlbum({
														filePath: res.tempFilePath,
														success: function () {
															that.percent = 100;
															
															console.log('save success');
															uni.showToast({
																icon:'success',
																duration:2000,
																title:'已保存到相册'
															})
														},
														fail: (errRes) => {
															that.targetMp4Download(type,downloadFileUrl)
														}
													})
													console.log("保存图片到相册")
												} 
											}else {
												uni.showModal({
													content:'资源无法访问，请联系作者反馈'
												})
											}
										},
										fail: function() {
											uni.hideLoading()
											uni.showModal({
												content: '下载失败，请复制无水印链接到浏览器下载'
											})
										}
										});
										downloadTask.onProgressUpdate((res) => {
											that.percent = res.progress;
											console.log(that.percent)
											if (res.progress == 100) {
												
											}
										});
								} else {
									uni.showModal({
										content: '资源文件暂时无法下载 请复制无水印链接到浏览器下载 有疑问请联系微信 ' +
											getApp().globalData.author
									})
			
								}
							},
							fail() {
								uni.hideLoading();
							},
							complete() {
								//uni.hideLoading()
							}
						});
					},
					fail: (res) => {
						uni.hideLoading();
						uni.showModal({
							content: '您没有同意相册权限,视频无法保存[请点击小程序右上角设置按钮 开启相册权限]'
						})
					}
				})
			},
			targetMp4Download:function(type,downloadUrl) {
				var that = this;
				uni.showToast({
					title:'保存相册中',
					icon:'loading'
				})
				that.percent = 0;
				that.fileStatus = 'active'
				var randomStr = Math.random().toString(36).substr(2);
				var fileType = null;
				if(type == 1) {
					fileType = randomStr + ".mp4"
				}else {
					fileType = randomStr + ".png"
				}
				var newFilePath = wx.env.USER_DATA_PATH+'/' + fileType;
				uni.showLoading({
					title:'下载中'
				})
				const downloadTask = uni.downloadFile({
					url: downloadUrl, 
					filePath:newFilePath,
					success: (res) => {
						uni.hideLoading();
						if (res.statusCode === 200) {
							if (type == 1) {
								uni.saveVideoToPhotosAlbum({
									filePath: newFilePath,
									success: function () {
										that.percent = 100;
										
										console.log('save success');
										uni.showToast({
											icon:'success',
											duration:2000,
											title:'已保存到相册'
										})
									},
									fail: (errRes) => {
										console.log('save error' + errRes);
									}
								});
								console.log("保存视频到相册")
							} else if (type == 2) {
								uni.saveImageToPhotosAlbum({
									filePath: newFilePath
								})
								that.percent = 100;
								
								console.log('save success');
								uni.showToast({
									icon:'success',
									duration:2000,
									title:'已保存到相册'
								})
							} 
						}else {
							uni.showModal({
								content:'资源无法访问，请联系作者反馈'
							})
						}
					},
					fail: function() {
						uni.hideLoading();
						uni.showModal({
							content: '下载失败，请复制无水印链接到浏览器下载'
						})
					}
					});
					downloadTask.onProgressUpdate((res) => {
						that.percent = res.progress;
						if (res.progress == 100) {
							
						}
					});
			},
			copyImgLink(i) {
				var that = this;
				uni.setClipboardData({
					data: that.picsList[i],
					success() {
						uni.setStorageSync(that.picsList[i], that.picsList[i])
					}
				})
			},
			copyVideoLink(i) {
				var that = this;
				uni.setClipboardData({
					data: that.videosList[i],
					success() {
						uni.setStorageSync(that.videosList[i], that.videosList[i])
					}
				})
			},
			
			downAllFun() {
				var that = this;
				uni.showLoading({
					title:'初始化资源'
				})
				uni.request({
					url:that.$reqUrl + "/lyz/getUserAdTimes?uid="+getApp().globalData.uid,
					method:'get',
					success(res) {
						if(res.data.data < getApp().globalData.watchTimes && that.adError == 0) {
							uni.showModal({
								content:getApp().globalData.adTip,
								success(confirmRes) {
									if(confirmRes.confirm) {
										that.rewardedVideoAd.show().catch(() => {
											that.rewardedVideoAd.load()
											  .then(() => that.rewardedVideoAd.show())
											  .catch(err => {that.startAllDownload()})
										  })
									}else {
										uni.showToast({
											title:'看完广告即可下载视频哟',
											icon:'none'
										})
									}
								},
								fail(failRes) {
									
								}
							})
						}else {
							that.startAllDownload()
						}
					},complete(res) {
						uni.hideLoading()
					}
				})
			},
			
			async startAllDownload() {
				var that = this;
					var productList = that.tapType == 'video' ? that.videosList : that.picsList
					console.log(that.tapType)
					console.log(productList)
				for (var i = 0; i < productList.length; i++) {
					var curNum = i + 1;
					uni.showLoading()
					try {
						var playAddr = "";
						await this.getDownloadAddress(productList[i]).then(res => {
							console.log(res) //此处返回值是上面的resolve(res)的数据
							playAddr = res.data.data
						}).catch(err => {
							console.log(err) //此处返回值是上面reject(err);的数据
						})
						console.log('准备下载的图片地址:' + playAddr)
						await this.signleDownload(playAddr)
					} catch (e) {
						console.log(e)
					} finally {
						uni.hideLoading();
					}
				}
			
			},
			getDownloadAddress(imgUrl) {
				var that = this;
				return new Promise((resolve, reject) => {
					uni.request({
						url: that.$reqUrl + '/lyz/getDownLoadFileUrl',
						method: "POST",
						data: {
							link: imgUrl,
							type: 2,
							source: that.$source
						},
						success: (res) => {
							resolve(res);
						},
						fail: (failRes) => {
							reject(failRes);
						}
					});
				})
			},
			signleDownload(imgUrl) {
				let that = this
				return new Promise((resolve, reject) => {
					const downloadTask = uni.downloadFile({
						url: imgUrl,
						success: (res) => {
							if (res.statusCode === 200) {
								if (that.pageType == 'img') {
									uni.saveImageToPhotosAlbum({
										filePath: res.tempFilePath
									});
								} else {
									uni.saveVideoToPhotosAlbum({
										filePath: res.tempFilePath,
										success: function() {
											uni.showToast({
												icon: 'success',
												duration: 2000,
												title: '已保存到相册'
											})
										},
									});
								}
			
							}
							resolve(res);
						},
						fail: (failRes) => {
							reject(failRes);
						}
					});
				})
			},
			changeVideo(e) {
				console.log(e)
				this.videoIndex = e.detail.current
			},
			changeImg(e) {
				// this.imgIndex = index
				this.imgIndex = e.detail.current
			},
			
		}
	}
</script>

<style>
.video-play {
	width: 100%;
	height: 180px;
	margin-top: 10px;
}
.text-area {
	background: white;
	margin-top: 10px;
	margin-left: 10px;
	margin-right: 10px;
	border-radius: 8px;
}

.tower-swiper .tower-item {
		transform: scale(calc(0.5 + var(--index) / 10));
		margin-left: calc(var(--left) * 100upx - 150upx);
		z-index: var(--index);
	}
	
.clearBtn {
	color: white;
	background-color:  #16A7F8;
	width: 120px;
}

.teach {
	text-align: center;
	color: #16A7F8;
	text-decoration:underline
}

.tap-warp {
		display: flex;
		align-items: center;
		justify-content: space-around;
		color: #1890FF;
		margin-bottom: 8px;
	}

	.tap-item {
		font-size: 16px;
		display: flex;
		width: 25%;
		text-align: center;
		justify-content: center;
		padding-bottom: 10px;
		border-bottom: 1px solid transparent;
		/* align-items: center; */
	}

	.tap-item.active {
		border-bottom: 1px solid #1890FF;
	}

	.tap-item text {
		margin-left: 2px;
	}

	.swiper-box {
		height: 200px;
		background-color: #000;
	}

	.swiper-item .swiper-item-img {
		height: 200px !important;
		margin: 0 auto;
	}

	.swiper-tip {
		font-size: 10px;
		padding: 0 4px;
		border-radius: 4px;
		border: 1px solid #ddd;
		margin: 5px 0;
		line-height: 20px;
		display: flex;
		justify-content: space-between;
	}

	.operate-warp {
		margin-top: 8px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.operate-btn {
		border: 1px solid #1890FF;
		border-radius: 4px;
		padding: 5px 7px 5px 5px;
		display: inline-block;
		color: #1890FF;
	}

	.operate-btn.primary {
		border: 1px solid #1890FF;
		background: #1890FF;
		color: #fff;
	}
	.desc-warp{
		margin: 10px 0;
	}
</style>
